<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div style="margin-bottom: 15px;">
        <form action="" ;id="info">
            <input type="text" id="username" placeholder="请输入姓名">
            <input type="text" id="sex" placeholder="请输入性别">
            <input type="text" id="age" placeholder="请输入年龄">
            <input type="submit" value="提交" id="btn">
        </form>
    </div>
    <table border="1" width="540">
        <thead>
            <tr>
                <td>姓名</td>
                <td>性别</td>
                <td>年龄</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script>
// 渲染
        const tbody = document.querySelector('tbody')
        const arr = localStorage.getItem('s-data') ? JSON.parse(localStorage.getItem('s-data')) : []
        
        function render() {
            const htmlStr = []
            for (let i = 0; i < arr.length; i++) {
                htmlStr.push(
                    `
            <tr>
                <td>${arr[i].username}</td>
                <td>${arr[i].sex}</td>
                <td>${arr[i].age}</td>
                <td> <a href="javascript:;" data-id=${i}>删除</a></td>
            </tr>
            `
                )
            }
            tbody.innerHTML = htmlStr.join('')
        }
        render()
// 录入
        const info = document.querySelector('form')
        const items = info.querySelectorAll('[placeholder]')
        info.addEventListener('submit',function(e){
            e.preventDefault()
            const obj={}
          for(let i=0;i<items.length;i++){
           const item=items[i]
           console.log(item);
           if(item.value===''){
            return alert('输入一个东西')
           }
           obj[item.id]=item.value
           
          }
         
        arr.push(obj)
        // 录入存数据
        localStorage.setItem('s-student',JSON.stringify(arr))
        console.log(obj);
        render( )
        this.reset()
        })
// 删除
     tbody.addEventListener('click',function(e){
       if(e.target.tagName==='A'){
        arr.splice(e.target.dataset.id,1)
       }
      
       localStorage.setItem('s-student',JSON.stringify(arr))
       render()
     })


    </script>
</body>

</html>